<template>
  <div>
    <a-upload
      list-type="picture-card"
      v-model:file-list="fileList"
      :beforeUpload="beforeUpload"
      @preview="handlePreview"
    >
      <!-- 只允许上传一张图片 -->
      <div v-if="fileList.length < 1">
        <loading-outlined v-if="isImageUploading"/>
        <plus-outlined v-else/>
        <div class="ant-upload-text"> 图片上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="icon" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs} from 'vue';
import {message} from 'ant-design-vue';
import {uploadApi} from "/@/api/sys/upload";
import {HttpResult} from "/@/api/core/model/coreModel";
import {useGlobSetting} from "/@/hooks/setting";
import {onMounted} from "@vue/runtime-core";

export default defineComponent({

  name: 'ImageUpload',
  props: {
    icon: {
      type: String,
      required: true,
    },
  },
  emits: ['update:files'],
  setup(props, {emit}) {

    const data = reactive({
      file_id: props.icon,
      fileList: [] as any,
      previewVisible: false,
      previewImage: '',
      isImageUploading: false,
    });

    const beforeUpload = (file: any) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG格式的文件!');
      }
      const isLt2M = file.size / 1024 / 1024 < 3;
      if (!isLt2M) {
        message.error('图像必须小于2MB!');
      }
      if (isJpgOrPng && isLt2M) {
        data.isImageUploading = true;
        uploadApi(
          {file: file}, {}).then((result: HttpResult) => {
          if (result.code == 0) {
            data.file_id = result.data.filed_id;
            emit("update:files", data.file_id);
          }
          data.isImageUploading = false;
        });
      }
      // 此处设置为false, 可以禁止默认的文件上传
      return false;
    };

    const handlePreview = async (file: any) => {
      if (!file.url && !file.preview) {
        file.preview = (await getBase64(file.originFileObj)) as string;
      }
      data.previewImage = file.url || file.preview;
      data.previewVisible = true;
    };
    const handleCancel = () => {
      data.previewVisible = false;
    };

    function getBase64(file: File) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    }

    function getFileList() {
      if (data.file_id != null && data.file_id != '') {
        const {fileServerUrl = ''} = useGlobSetting();
        data.fileList = [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: fileServerUrl + '/' + data.file_id
          }
        ]
      }
    }

    onMounted(() => {
      // 初始化产品图标
      getFileList();
    });

    return {
      ...toRefs(data),
      beforeUpload,
      handlePreview,
      handleCancel
    }

  }
});

</script>

<style scoped></style>
